package com.dongwu.config;

import com.dongwu.common.constants.TencentIMConstants;
import com.dongwu.common.utils.mapper.JaxbMapper;
import com.dongwu.manager.dto.WeiXinTransfers;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.security.KeyStore;
import java.util.Map;
import java.util.UUID;

/**
 * 微信企业付款拼接参数
 * 
 * @author xyj
 *
 */
public class TransfersConfig {

	private static Logger logger = LoggerFactory.getLogger(TransfersConfig.class);

	public String transfers(String openId,Integer amount) throws Exception {
		WeiXinTransfers transfers=new WeiXinTransfers();
		String nonce = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 30);
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		transfers.setMch_appid(TencentIMConstants.WEIXINAPPID);// 自己的公众账号
		transfers.setMchid(TencentIMConstants.WEIXINBUSSINESID);//自己的 商户号
		transfers.setNonce_str(nonce);// 随机字符串
		transfers.setOpenid(openId);// 用户openId
		transfers.setCheck_name("NO_CHECK");// 校验用户姓名选项
		//transfers.setRe_user_name("ZS");
		transfers.setAmount(amount*100);// 付款金额
		transfers.setDesc("微信企业付款");// 企业付款描述信息
		transfers.setSpbill_create_ip("172.24.171.81");// 调用接口的机器Ip地址
		transfers.setPartner_trade_no(uuid);// 商户订单号
		String sign = createSendRedPackOrderSign(transfers);
		transfers.setSign(sign);// 签名
		logger.info("transfers: " + transfers.toString());
		String xml = JaxbMapper.toXml(transfers);
		String response = SSL(TencentIMConstants.WEIXINTRANSFERS,xml);
		Map<String, String> return_msg = JaxbMapper.parseXml(response);
		return return_msg.toString();
	}

	public static String createSendRedPackOrderSign(WeiXinTransfers transfers) {
		StringBuffer sign = new StringBuffer();
		sign.append("amount=").append(transfers.getAmount());
		sign.append("&check_name=").append(transfers.getCheck_name());
		sign.append("&desc=").append(transfers.getDesc());
		sign.append("&mch_appid=").append(transfers.getMch_appid());
		sign.append("&mchid=").append(transfers.getMchid());
		sign.append("&nonce_str=").append(transfers.getNonce_str());
		sign.append("&openid=").append(transfers.getOpenid());
		sign.append("&partner_trade_no=").append(transfers.getPartner_trade_no());
		//sign.append("&re_user_name=").append(transfers.getRe_user_name());
		sign.append("&spbill_create_ip=").append(transfers.getSpbill_create_ip());
		sign.append("&key=").append(TencentIMConstants.WEIXINBUSSINESKEY);
		return DigestUtils.md5Hex(sign.toString()).toUpperCase();
	}

	@SuppressWarnings("deprecation")
	private static String SSL(String url, String data) {
		StringBuffer message = new StringBuffer();
		File WeiXinCertificate = null; // 微信商户证书
		// 获取当前系统类型
		String os = System.getProperty("os.name");
		if (os.toLowerCase().startsWith("win")) {
			try {
				// windows下获取jnisigcheck.dll的绝对路径
				WeiXinCertificate = ResourceUtils.getFile("classpath:WeiXinCertificate/apiclient_cert.p12");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			WeiXinCertificate = new File(TencentIMConstants.WEIXINCERTIFIICATEFORLINUX);
		}
		try {
			KeyStore keyStore = KeyStore.getInstance("PKCS12");
			FileInputStream instream = new FileInputStream(WeiXinCertificate);
			keyStore.load(instream, TencentIMConstants.WEIXINBUSSINESID.toCharArray());
			SSLContext sslcontext = SSLContexts.custom()
					.loadKeyMaterial(keyStore, TencentIMConstants.WEIXINBUSSINESID.toCharArray()).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
					null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
			HttpPost httpost = new HttpPost(url);
			httpost.addHeader("Connection", "keep-alive");
			httpost.addHeader("Accept", "*/*");
			httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			httpost.addHeader("Host", "api.mch.weixin.qq.com");
			httpost.addHeader("X-Requested-With", "XMLHttpRequest");
			httpost.addHeader("Cache-Control", "max-age=0");
			httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
			httpost.setEntity(new StringEntity(data, "UTF-8"));
			CloseableHttpResponse response = httpclient.execute(httpost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					BufferedReader bufferedReader = new BufferedReader(
							new InputStreamReader(entity.getContent(), "UTF-8"));
					String text;
					while ((text = bufferedReader.readLine()) != null) {
						message.append(text);
					}
				}
				EntityUtils.consume(entity);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				response.close();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return message.toString();
	}

}
